<template>
    <div>
        <el-card>
            <!-- 卡片头部区域 -->
            <template #header>
                <div class="card-header">
                    <span class="header-title">生产计划</span>
                </div>
            </template>

            <!-- 主要内容区域 -->
            <el-space direction="vertical" style="width: 100%; align-items: normal; gap: 15px 0;">
                <!-- 搜索表单 -->
                <el-form :model="formData" ref="form" label-width="80px" :inline="true">
                    <el-row :gutter="24">
                        <!-- 计划编号输入框 -->
                        <el-col :span="8" :offset="0">
                            <el-form-item label="计划编号" prop="planCode">
                                <el-input placeholder="请输入计划编号" size="large" v-model="formData.planCode" clearable />
                            </el-form-item>
                        </el-col>

                        <!-- 计划名称输入框 -->
                        <el-col :span="8" :offset="0">
                            <el-form-item label="计划名称" prop="planName">
                                <el-input placeholder="请输入计划名称" size="large" v-model="formData.planName" clearable />
                            </el-form-item>
                        </el-col>

                        <!-- 订单编号输入框 -->
                        <el-col :span="8" :offset="0">
                            <el-form-item label="订单编号">
                                <el-input placeholder="请输入产品编号" size="large" v-model="formData.salesOrderId"
                                    clearable />
                            </el-form-item>
                        </el-col>
                    </el-row>



                    <el-row :gutter="20">
                        <!-- 开始时间选择器 -->
                        <el-col :span="8" :offset="0">
                            <el-form-item label="开始时间" prop="startDate">
                                <el-date-picker type="datetime" placeholder="选择日期" v-model="formData.startDate"
                                    size="large" value-format="YYYY-MM-DD HH:mm:ss" />
                            </el-form-item>
                        </el-col>

                        <!-- 结束时间选择器 -->
                        <el-col :span="8" :offset="0">
                            <el-form-item label="结束时间" prop="endDate">
                                <el-date-picker type="datetime" placeholder="选择日期" v-model="formData.endDate"
                                    size="large" value-format="YYYY-MM-DD HH:mm:ss" />
                            </el-form-item>
                        </el-col>

                        <!-- 操作按钮 -->
                        <el-col :span="8" :offset="0" style="padding-left: 50px;">
                            <el-form-item>
                                <el-button type="primary" @click="handleSearch">搜索</el-button>
                                <el-button type="info" :plain="true" @click="resetForm">重置</el-button>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>

                <!-- 操作按钮区域 -->
                <el-row :gutter="20">
                    <el-col :span="24">
                        <el-button @click="toInsert" type="primary" :plain="true">+添加</el-button>
                        <el-button type="success" :plain="true" :disabled="!currentRow" @click="toUpdate">修改</el-button>
                        <el-button type="danger" :plain="true" :disabled="!currentRow"
                            @click="handleDelete(currentRow)">删除</el-button>
                    </el-col>
                </el-row>

                <!-- 数据表格 -->
                <el-table :data="page.records" style="width: 100%" border highlight-current-row
                    @current-change="handleCurrentChange" @row-click="handleRowClick">

                    <!-- 计划编号列（可点击查看详情） -->
                    <el-table-column label="计划编号" prop="planCode">
                        <template #default="{ row }">
                            <el-link type="primary" @click.stop="openDetailDialog(row)">{{ row.planCode }}</el-link>
                        </template>
                    </el-table-column>

                    <!-- 计划名称列 -->
                    <el-table-column label="计划名称" prop="planName" />

                    <!-- 订单编号列 -->
                    <el-table-column label="订单编号" prop="salesOrderId" />

                    <!-- 计划类型列 -->
                    <el-table-column label="计划类型">
                        <template #default="{ row }">
                            {{ formatPlanType(row.planType) }}
                        </template>
                    </el-table-column>

                    <!-- 计划开始日期列 -->
                    <el-table-column label="计划开始日期" prop="startDate" />

                    <!-- 计划结束日期列 -->
                    <el-table-column label="计划结束日期" prop="endDate" />

                    <!-- 计划状态列 -->
                    <el-table-column label="计划状态">
                        <template #default="{ row }">
                            {{ formatPlanStatus(row.planStatus) }}
                        </template>
                    </el-table-column>

                    <!-- 操作列 -->
                    <el-table-column label="操作" fixed="right">
                        <template #default="{ row }">
                            <el-button type="primary" size="small" @click.stop="handleEdit(row)"
                                :row="row">修改</el-button>
                            <el-button type="danger" size="small" @click.stop="handleDelete(row)"
                                :disabled="row.planStatus != 1">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-space>

            <!-- 分页组件 -->
            <el-pagination @current-change="loadData" v-model:currentPage="page.current" :page-sizes="[2, 4, 6, 8, 10]"
                :page-size="page.size" :total="page.total" background>
            </el-pagination>

            <!-- 详情对话框 -->
            <el-dialog :title="dialogTitle" v-model="dialogVisible" width="60%" :destroy-on-close="true" @closed="handleDialogClosed">
                <router-view @ref-table="refTable" :data="currentRow"></router-view>
            </el-dialog>
        </el-card>
    </div>
</template>

<script setup>
import { ref ,onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { data } from 'jquery'
import request from '@/api/request.js'


const router = useRouter()


// 刷新表格数据
const refTable = () => {
    dialogVisible.value = false
}


// 格式化计划类型显示
const formatPlanType = (type) => {
    if (!type) return '-'
    const typeMap = {
        '1': '销售订单',
        '2': '库存计划'
        // 可以添加其他映射关系
    }
    return typeMap[type] || type
}

// 格式化计划状态显示
const formatPlanStatus = (status) => {
    if (!status) return
    const statusMap = {
        '1': '未开始',
        '2': '已确认',
        '4': '已取消'
        // 可以添加其他映射关系
    }
    return statusMap[status] || status
}

// 分页数据
const page = ref({
    current: 1,    // 当前页码
    size: 10,      // 每页显示条数
    total: 0,      // 总条数
    records: []    // 当前页数据
})

// 表单数据
const formData = ref({})

// 当前选中行
const currentRow = ref(null)
// 对话框可见性
const dialogVisible = ref(false)
// 对话框标题
const dialogTitle = ref('')

// 加载数据
const loadData = () => {
    // 构造查询参数
    const params = {
        current: page.value.current,
        size: page.value.size,
        ...formData.value
    }

    request({
        url: '/production/plan/page',
        method: 'GET',
        params
    }).then(res => {
        page.value = res.data
        console.log(page.value)
    })
}

// 初始化加载数据
loadData()

// 搜索处理
const handleSearch = () => {
    page.value.current = 1  // 搜索时重置到第一页
    console.log(formData.value)
    loadData()
}

// 重置表单
const resetForm = () => {
    formData.value = {}
    handleSearch()  // 重置后重新加载数据
}

// 当前行变化处理
const handleCurrentChange = (row) => {
    currentRow.value = row
}

// 行点击处理
const handleRowClick = (row) => {
    currentRow.value = row
}

// 处理弹窗关闭
const handleDialogClosed = () => {
    dialogVisible.value = false
    router.push('/production/order')
    loadData()
}

// 打开详情对话框
const openDetailDialog = (row) => {
    dialogTitle.value = "计划详情"
    currentRow.value = row
    dialogVisible.value = true
    router.push("/production/plan/list")

}

// 跳转到添加页面
const toInsert = () => {
    dialogTitle.value = "添加生产计划"
    currentRow.value = null
    dialogVisible.value = true
    router.push('/production/plan/insert')
}

// 跳转到修改页面
const toUpdate = () => {
    if (!currentRow.value) return
    dialogTitle.value = "修改生产计划"
    dialogVisible.value = true
    router.push("/production/plan/update")
}

// 编辑处理
const handleEdit = (row) => {
    currentRow.value = row
    if (row != null) {
        data.value = row
        console.log(data.value)
    }
    toUpdate()
}

// 删除处理
const handleDelete = (row) => {
    ElMessageBox.confirm(`确定要删除计划【${row.planName}】吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        if (row.planStatus != 1) {
            ElMessage.error('该计划已开始生产，不能删除')
            return
        }
        request({
            url: `/production/plan/delete`,
            method: 'put',
            params: { planId: row.planId }

        }).then(() => {
            console.log(row.planId)
            ElMessage.success('删除成功')
            loadData()  // 重新加载数据
            if (currentRow.value && currentRow.value.planId === row.planId) {
                currentRow.value = null
            }
        })
    })
}
</script>

<style scoped>
.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.header-title {
    font-size: 18px;
    font-weight: bold;
}

.el-table {
    margin-top: 15px;
}

.el-pagination {
    margin-top: 15px;
    justify-content: flex-end;
}
</style>